import 'package:flutter/material.dart';
import 'package:hi_flutter/app_page.dart';

class GridViewDemoPage extends StatefulWidget {
  const GridViewDemoPage({super.key});

  @override
  State<GridViewDemoPage> createState() => _GridViewDemoPageState();
}

/// SliverGridDelegateWithFixedCrossAxisCount  横轴子元素的数量。此属性值确定后子元素在横轴的长度就确定了，即ViewPort横轴长度除以crossAxisCount的商
/// SliverGridDelegateWithMaxCrossAxisExtent   maxCrossAxisExtent为子元素在横轴上的最大长度，之所以是“最大”长度，是因为横轴方向每个子元素的长度仍然是等分的
class _GridViewDemoPageState extends State<GridViewDemoPage> {
  List<IconData> iconList = [];

  @override
  void initState() {
    // TODO: implement initState
    _retrieveIcons();
    super.initState();
  }

  //模拟异步获取数据
  void _retrieveIcons() {
    Future.delayed(const Duration(milliseconds: 200)).then((e) {
      setState(() {
        iconList.addAll([
          Icons.ac_unit,
          Icons.airport_shuttle,
          Icons.all_inclusive,
          Icons.beach_access,
          Icons.cake,
          Icons.free_breakfast,
        ]);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return AppPage(
      body: GridView.builder(
        itemCount: iconList.length,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3, //每行三列
          childAspectRatio: 1.0, //显示区域宽高相等
        ),
        itemBuilder: (context, index) {
          //如果显示到最后一个并且Icon总数小于200时继续获取数据
          if (index == iconList.length - 1 && iconList.length < 200) {
            _retrieveIcons();
          }
          return Icon(iconList[index]);
        },
      ),
    );
  }
}
